package com.kou.controller;/**
 * @author SteinY
 * @create 2022-03-24 21:32
 * @description:
 */

import com.kou.pojo.Cart;
import com.kou.pojo.Goods;
import com.kou.pojo.User;
import com.kou.service.CartService;
import com.kou.service.GoodsService;
import com.kou.service.impl.CartServiceImpl;
import com.kou.service.impl.GoodsServiceImpl;
import com.kou.utils.Constants;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * projectName:myshop2
 * author:SteinY
 * time:2022/3/24 21:32
 * description:
 */
@WebServlet("/cart")
public class CartServlet extends BaseServlet {
    CartService cartService = new CartServiceImpl();
    GoodsService goodsService = new GoodsServiceImpl();
    public String create(HttpServletRequest request, HttpServletResponse response){
        String pid = request.getParameter("pid");
        User user = (User) request.getSession().getAttribute("loginUser");
        int uid = user.getId();

        Cart cart = cartService.findCart(pid, uid);
        if (cart!=null){
            Goods goods = goodsService.findGoodsById(pid);
            return Constants.FORWARD + "cart?method=update&cid="+cart.getCid()+"&cnum="+(cart.getNum()+1)+"&price="+goods.getPrice();

        }else {
            cartService.create(pid,uid);

            //进入购物车添加成功页面  无须显示任何信息
            return Constants.FORWARD + "cartSuccess.jsp";
        }

    }
    public String show(HttpServletRequest request, HttpServletResponse response){
        String uid = request.getParameter("uid");

        List<Cart> carts = cartService.findCarts(uid);

        request.setAttribute("list",carts);
        //进入购物车添加成功页面  无须显示任何信息
        return Constants.FORWARD + "cart.jsp";
    }

    //删除购物车数据
    public String delete(HttpServletRequest request, HttpServletResponse response){
        String cid = request.getParameter("cid");
        cartService.delete(cid);

        User user = (User) request.getSession().getAttribute("loginUser");
        return Constants.FORWARD + "/cart?method=show&uid="+user.getId();
    }
    //更新购物车数据（增加或减少）
    public String update(HttpServletRequest request, HttpServletResponse response){
        String cid = request.getParameter("cid");
        String cnum = request.getParameter("cnum");
        String price = request.getParameter("price");

        cartService.update(cid,cnum,price);
        User user = (User) request.getSession().getAttribute("loginUser");
        return Constants.FORWARD + "/cart?method=show&uid="+user.getId();
    }

    public String clear(HttpServletRequest request, HttpServletResponse response){
        String uid = request.getParameter("uid");
        cartService.clear(uid);

        User user = (User) request.getSession().getAttribute("loginUser");
        return Constants.FORWARD + "/cart?method=show&uid="+user.getId();
    }
}